package com.micro.magupe.auth.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.micro.magupe.auth.entity.User;
import com.micro.magupe.auth.vo.UserDetailsImpl;
import com.micro.magupe.common.util.CollectionsUtil;
import com.micro.magupe.common.vo.MenuVO;

@Service
public class MicroUserDetailsService implements UserDetailsService{

	@Autowired
	UserService userService;
	@Autowired
	MenuService menuService;
	
	@Override
	public UserDetailsImpl loadUserByUsername(String username) throws UsernameNotFoundException {
		List<MenuVO> menus = menuService.listByUserId2(username);
		if(CollectionsUtil.isEmpty(menus)) {
			throw new UsernameNotFoundException("用户: " + username + ", 不存在!");
		}
		
		User user = null;
		try {
			MenuVO menuVO = menus.get(0);
			user = new User();
			user.setId(menuVO.getUserId());
			user.setName(menuVO.getName());
			user.setUsername(menuVO.getUsername());
			user.setPassword(menuVO.getPassword());
		} catch (Exception e) {
			throw new UsernameNotFoundException("用户: " + username + ", 不存在!");
		}
		
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if(!CollectionsUtil.isEmpty(menus)){
        	for (MenuVO menu : menus) {
                if(StringUtils.isNotBlank(menu.getPerms())){
                	GrantedAuthority authorityM = new SimpleGrantedAuthority("ROLE_" + menu.getPerms());
                	authorities.add(authorityM);
                }
			}
        }

        UserDetailsImpl u = new UserDetailsImpl(user.getUsername(), user.getPassword(), authorities);
		u.setId(user.getId());
		u.setName(user.getName());
		return u;
	}
/*	
	@Override
	public UserDetailsImpl loadUserByUsername(String username) throws UsernameNotFoundException {
		UserVO user = userService.searchByUsername(username);
		if(user == null) {
			throw new UsernameNotFoundException("用户: " + username + ", 不存在!");
		}
		
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		List<MenuVO> menus = menuService.listByUserId(user.getId());
		if(!CollectionsUtil.isEmpty(menus)){
			for (MenuVO menu : menus) {
				if(StringUtils.isNotBlank(menu.getPerms())){
					GrantedAuthority authorityM = new SimpleGrantedAuthority("ROLE_" + menu.getPerms());
					authorities.add(authorityM);
				}
			}
		}
		
		UserDetailsImpl u = new UserDetailsImpl(user.getUsername(), user.getPassword(), authorities);
		u.setId(user.getId());
		u.setName(user.getName());
		return u;
	}
*/
}
